from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from inc.models import db, AdminDepartment, AdminMember
from .utils import admin_required

# 创建蓝图
dept_bp = Blueprint('department', __name__, url_prefix='/admin/department')


@dept_bp.route('/')
@login_required
@admin_required
def department_list():
    """部门列表"""
    departments = AdminDepartment.query.options(
        db.joinedload(AdminDepartment.children)
    ).all()
    return render_template('admin/department/jira_list.html', departments=departments)


@dept_bp.route('/<int:dept_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def department_detail(dept_id):
    """部门详情及审批人管理"""
    department = AdminDepartment.query.get_or_404(dept_id)
    all_members = AdminMember.query.filter_by(status=True).all()

    if request.method == 'POST':
        # 更新部门基本信息
        department.name = request.form.get('name')
        department.order_num = request.form.get('order_num', type=int) or 0

        # 更新审批人
        approver_ids = request.form.getlist('approver_ids')
        department.set_approvers(approver_ids)

        db.session.commit()
        flash('部门信息已更新', 'success')
        return redirect(url_for('department.department_detail', dept_id=dept_id))

    # 获取部门成员
    members = AdminMember.query.filter_by(department_id=dept_id, status=True).all()

    return render_template('admin/department/jira_detail.html',
                           department=department,
                           members=members,
                           all_members=all_members)